import { createContext, useState, useEffect, useMemo } from 'react';

export const AuthContext = createContext();
export function AuthProvider({ children }) {
    const [authState, setAuthState] = useState({
        token: null,
        username: null,
        privilegeLevel: null
    });

    // 初始化时从 localStorage 恢复状态
    useEffect(() => {
        const token = localStorage.getItem('enc_token');
        const username = localStorage.getItem('username');
        const privilegeLevel = localStorage.getItem('privilege_level');

        if (token && username) {
            setAuthState({ token, username, privilegeLevel });
        }
    }, []);

    // 登录方法（直接存储原始 token）
    const login = (token, userData) => {
        localStorage.setItem('enc_token', token);
        localStorage.setItem('username', userData.username);
        localStorage.setItem('privilege_level', userData.privilegeLevel);

        setAuthState({
            token,
            username: userData.username,
            privilegeLevel: userData.privilegeLevel
        });
    };

    // 退出方法
    const logout = () => {
        localStorage.clear();
        setAuthState({ token: null, username: null, privilegeLevel: null });
    };

    return (
        <AuthContext.Provider value={{
            ...authState,
            login,
            logout
        }}>
            {children}
        </AuthContext.Provider>
    );
}